package ng.map.collision;

import java.awt.Graphics2D;

import ng.Paintable;
import ng.lib.Vector2D;

/**
 * Stellt ein {@link CollisionBound} in der Form eines Kreises dar.
 * @author Martin Spielmann
 *
 */
public class CollisionCircle implements CollisionBound {
	private Vector2D position;
	private int radius;

	public CollisionCircle(Vector2D p, int r) {
		this.position = p;
		this.radius = r;
	}

	public int getRadius() {
		return radius;
	}

	public Vector2D getPosition() {
		return position;
	}

	public Vector2D getCenterPosition() {
		return position.clone().add(new Vector2D(this.radius, this.radius));
	}

	@Override
	public boolean isColliding(CollisionBound cb, Vector2D offset) {

		if (cb instanceof CollisionCircle) {
			Vector2D d = (((CollisionCircle) cb).getCenterPosition().add(offset).minus(this.getCenterPosition()));
			
			return ((d.x*d.x+d.y*d.y) < Math.pow((this.radius+((CollisionCircle) cb).radius),2));
			
		} else if (cb instanceof CollisionRectangle) {
			
			Vector2D rectPo = ((CollisionRectangle) cb).getPosition().clone().add(offset);
			
			int dx = (int) Math.abs(this.getCenterPosition().x - rectPo.x
					- ((CollisionRectangle) cb).getWidth() / 2);
			int dy = (int) Math.abs(this.getCenterPosition().y - rectPo.y
					- ((CollisionRectangle) cb).getHeight() / 2);

			if (dx > (((CollisionRectangle) cb).getWidth() / 2 + this.radius)) {
				return false;
			}
			if (dy > (((CollisionRectangle) cb).getHeight() / 2 + this.radius)) {
				return false;
			}

			if (dx <= (((CollisionRectangle) cb).getWidth() / 2)) {
				return true;
			}
			if (dy <= (((CollisionRectangle) cb).getHeight() / 2)) {
				return true;
			}

			int cd = (int) Math
					.sqrt((dx - ((CollisionRectangle) cb).getWidth() / 2) ^ 2
							+ (dy - ((CollisionRectangle) cb).getHeight() / 2)
							^ 2);

			return (cd <= this.radius);

		}

		return false;
	}

	@Override
	public void draw(Graphics2D g2, Vector2D v) {
		g2.drawOval((int) (v.x + position.x), (int) (v.y + position.y),
				2 * radius, 2 * radius);
	}

}
